<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>列表过滤排序-监测原理</title>
    <script type="text/javascript" src="./js/vue.js"></script>
    <style>
        .basic {
            width: 400px;
            height: 100px;
            border: 1px solid black;
        }
    </style>
</head>
<div id="root">
    <h2>{{name}}</h2>
    <input type="text" placeholder="请输入名字" v-model="keyWord" />
    <button @click="sortType=2">按年龄升序</button>
    <button @click="sortType=1">按年龄降序</button>
    <button @click="sortType=0">按年龄升序</button>
    <br>
    <button @click="updateMei">更新马冬梅</button>
    <button @click="vSet">Vue.set</button>
    <ul>
        <li v-for="(p,index) in filterPersons" ::key="p.id">
            {{p.name}}--{{p.sex}}--{{p.age}}--{{p.phone}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;

    const vm = new Vue({
        el: '#root',
        data: {
            name: '培立优',
            keyWord: '',
            sortType: 0,// 0 原顺序 1 降序 2 升序
            persons: [
                { id: '001', name: '马冬梅', age: 29, sex: '女' },
                { id: '002', name: '周冬雨', age: 19, sex: '女' },
                { id: '003', name: '汉高祖', age: 39, sex: '男' },
                { id: '004', name: '明太祖', age: 26, sex: '男' },
            ],
            //filterPersons: []
        },
        //#region 
        computed: {
            filterPersons() {
                return this.persons.filter((p) => {
                    return -1 !== p.name.indexOf(this.keyWord);
                }).sort((p1, p2) => {
                    if (1 === this.sortType) {
                        return p2.age - p1.age;
                    } else if (2 === this.sortType) {
                        return p1.age - p2.age;
                    }
                    return true;
                });
            }
        },
        //#endregion
        //#region watch实现过滤
        // watch: {
        //     keyWord: {
        //         immediate: true,
        //         handler(nVal, oVal) {
        //             console.log(nVal);
        //             this.filterPersons = this.persons.filter((p) => {
        //                 return -1 !== p.name.indexOf(nVal);
        //             });
        //         },
        //     }
        // },
        //#endregion
        methods: {
            updateMei() {
                //this.persons[0].name = '马老师';//奏效
                this.persons[0] = { id: '001', name: '马老师', age: 70, sex: '男' };//无效
                //this.persons.pop();//奏效
                // 数组 push pop splice reverse shift unshift 更新数组可以监控到
            },
            vSet() {
                Vue.set(vm._data.persons[0], 'phone', '130');
                vm.$set(vm._data.persons[1], 'phone', '133');
                Vue.set(vm._data.persons[2], 'phone', '188');
                Vue.set(vm._data.persons[3], 'phone', '189');
            }
        }
    });

</script>

</html>